package com.sqlcheck.entity;

import com.baomidou.mybatisplus.annotation.*;
import com.sqlcheck.common.enums.DatabaseType;
import com.sqlcheck.enums.TaskStatus;
import com.sqlcheck.util.JsonUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.time.LocalDateTime;
import java.util.Map;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName(value = "manual_sql_analysis")
public class ManualSqlAnalysis {

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    @TableField("task_id")
    private Long taskId;

    @TableField("sql_content")
    private String sqlContent;

    @TableField("sql_type")
    private SqlType sqlType;

    @TableField("source_db_type")
    private DatabaseType sourceDbType;

    @TableField("target_db_type")
    private DatabaseType targetDbType;

    @TableField("analysis_result")
    private String analysisResultJson;

    @TableField("compatibility_level")
    private CompatibilityLevel compatibilityLevel;

    @TableField(value = "created_at", fill = FieldFill.INSERT)
    private LocalDateTime createdAt;

    @TableField(value = "updated_at", fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updatedAt;

    @TableLogic
    @TableField("deleted")
    private Boolean deleted;

    // Additional fields for compatibility with service layer
    @TableField(exist = false)
    private String taskName;

    @TableField(exist = false)
    private TaskStatus status;

    @TableField(exist = false)
    private Integer issuesFound;

    @TableField(exist = false)
    private LocalDateTime createdTime;

    @TableField(exist = false)
    private LocalDateTime completedTime;

    // Helper methods for analysis_result JSON field
    public Map<String, Object> getAnalysisResult() {
        return JsonUtils.safeParseMap(this.analysisResultJson);
    }

    public ManualSqlAnalysis setAnalysisResult(Map<String, Object> analysisResult) {
        this.analysisResultJson = JsonUtils.safeToJsonString(analysisResult);
        return this;
    }

    public enum SqlType {
        QUERY, DML, DDL, PROCEDURE, FUNCTION, TRIGGER
    }

    public enum CompatibilityLevel {
        HIGH, MEDIUM, LOW, INCOMPATIBLE
    }
}